package com.hfzy.ihk.web.freeswitchCall.job.freeswitch;

import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.web.freeswitchCall.biz.PushDataToOracleBiz;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisFields;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * @Auther: Administrator
 * @Date: 2019/1/23 21:53
 * @Description:
 */
@Component
@Profile({"pro","dev"})
public class PushDataOracleJob {

    private static final Logger logger = LoggerFactory.getLogger(PushDataOracleJob.class);

    private static Boolean isDataJobfinish = false;

    private static Boolean isUrlJobfinish = false;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PushDataToOracleBiz pushDataToOracleBiz;


    /**
     * 检查freeswitch推送数据到Oracle失败的job 三分钟跑一次
     */
    @Scheduled(cron = "0 0/3 * * * ?")
    public void fsRePushRecord(){
        if(isDataJobfinish)
            return ;
        isDataJobfinish = true;
        //获得推送失败的数据
        try {
            Set<String> recordFailSet = redisTemplate.opsForSet().members(RedisKey.PUSH_RECORD_TO_ORACLE_FAILED_SET);
            logger.info(">>>>>>>>>>>>>>>FreeswitchCall执行补推数据到OracleJob redis 大小为：{}", recordFailSet.size());
            if (recordFailSet != null && recordFailSet.size() > 0) {
                for (String sessionId : recordFailSet) {
                    if (StringTools.isEmpty(sessionId) || "".equals(sessionId)) {
                        redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_ORACLE_FAILED_SET, sessionId);
                        continue;
                    }
                    Map<String, String> callHistoryMap = redisTemplate.opsForHash().entries(RedisKey.CALL_HISTORY_RPIX + sessionId);
                    if (StringTools.isNotempty(callHistoryMap) && callHistoryMap.size() > 0) {//不为空，推送
                        //pushDataToOracleBiz.jobPushData(callHistoryMap);
                        pushDataToOracleBiz.jobPushData(callHistoryMap);
                    } else {//为空，删了防止堆积
                        redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_ORACLE_FAILED_SET, sessionId);
                    }
                }
            }
        }catch (Exception e){
            logger.error(">>>>>重新推呼叫数据到oracle job 异常",e);
        }
        isDataJobfinish = false;
    }



}
